import { EventManagerService } from './../../../../../../services/event-manager.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { OrgCodeItem } from '../models';


@Component({
  selector: 'zepride-group-code-input',
  templateUrl: './group-code-input.component.html',
  styleUrls: ['./group-code-input.component.less']
})
export class GroupCodeInputComponent implements OnInit, OnDestroy {
  orgItem: OrgCodeItem;
  onAddItemHandle;
  onDelOrgCodeItemHandle;
  onResize;
  onDelete() {
    this.eventSvr.removeEvent(this.eventId);
    console.log('GroupCodeInputComponent, onDelete');
  }
  private eventId: string;
  constructor(
    private eventSvr: EventManagerService
  ) {
  }
  ngOnDestroy(): void {
    console.log('GroupCodeInputComponent, OnDestroy');
  }
  ngOnInit(): void {
    this.eventId = this.eventSvr.registEvent('groupBoxResize', this.groupBoxResizeHandle.bind(this))
  }

  private getMaxItemCount() {
    let list = this.orgItem.codeGroupItems.map(x => x.list.length);
    list = list.sort();
    return list[list.length - 1];
  }

  private groupBoxResizeHandle() {
    let wCount = this.getMaxItemCount();
    let hCount = this.orgItem.codeGroupItems.length;
    if (wCount == 0) {
      this.onDelOrgCodeItemHandle && this.onDelOrgCodeItemHandle(this.orgItem);
      this.eventSvr.removeEvent(this.eventId);
    }
    else {
      let ele: any = document.querySelector('#group-' + this.orgItem.id);
      ele.style.width = `${wCount * 180 + 100}px`;

      ele.style.height = `${hCount * 86}px`;
    }

    this.onResize && this.onResize();
  }

  onAllItemDelete() {
    let index = this.orgItem.codeGroupItems.findIndex(x => x.list.length == 0);
    this.orgItem.codeGroupItems.splice(index, 1);
  }

}
